<style lang="less" scoped>
@import "./list.less";
</style>
<template>
  <div>
    <input type="file" ref="upload" style="display:none" accept=".xls, .xlsx" />
    <Row>
      <Col span="24">
        <Card>
          <p slot="title" style="height: 32px">
            <Button type="primary" icon="md-add" @click="hanldleAdd()">选择数据源</Button>
            <Button type="primary" icon="md-add" @click="save()">保存至数据库</Button>
          </p>
          <div>
            <Table :columns="columnsList" :data="tableData" border disabled-hover></Table>
          </div>
          <div class="margin-top-15" style="text-align: center">
            <Page show-elevator show-sizer show-total></Page>
          </div>
        </Card>
      </Col>
    </Row>
  </div>
</template>
<script>
import XLSX from "xlsx";
import {
  getList,
  changeStatus,
  add,
  edit,
  del,
  getAppInfo,
  refreshAppSecretApi
} from "@/api/app";

const editButton = (vm, h, currentRow, index) => {
  return h(
    "Button",
    {
      props: {
        type: "primary"
      },
      style: {
        margin: "0 5px"
      },
      on: {
        click: () => {}
      }
    },
    vm.$t("edit_button")
  );
};
const deleteButton = (vm, h, currentRow, index) => {
  return h(
    "Button",
    {
      props: {
        type: "primary"
      },
      style: {
        margin: "0 5px"
      },
      on: {
        click: () => {
          vm.tableData.splice(index, 1);
          currentRow.loading = false;
        }
      }
    },
    vm.$t("delete_button")
  );
};

export default {
  name: "import_excel",
  data() {
    return {
      columnsList: [],
      tableData: []
    };
  },
  mounted() {
    this.$refs.upload.addEventListener("change", e => {
      // 绑定监听表格导入事件
      this.readExcel(e);
    });
  },
  created() {},
  methods: {
    hanldleAdd() {
      this.$refs.upload.click();
    },
    readExcel(e) {
      const that = this;
      let actionColumn = {
        //数据操作表头
        title: "操作",
        align: "center",
        width: 200,
        render: (h, params) => {
          return h("div", [
            editButton(that, h, params.row, params.index),
            deleteButton(that, h, params.row, params.index)
          ]);
        }
      };
      let column = {};
      const { files } = e.target;
      if (files.length <= 0) {
        return false;
      }
      if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
        this.$Message.error("上传格式不正确，请上传xls或者xlsx格式");
        return false;
      }

      const fileReader = new FileReader();
      fileReader.onload = ev => {
        try {
          const data = ev.target.result;
          const workbook = XLSX.read(data, {
            type: "binary"
          });
                  
          const wsname = workbook.SheetNames[0]; // 取第一张表
          
          const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); // 生成json                 表格内容
            console.log(ws[0]);
          if (ws.length > 0) {
            this.data = [];
            let id = 0;
            ws.forEach(info => {
              let Discount = 0;
              if (info["优惠券面额"] !== "无") {
                Discount = parseFloat(
                  info["优惠券面额"].match(/(减=?)(\S*)(?=元)/)[2]
                );
              }
              this.data.push({
                key: id,
                GoodsId: info["商品id"],
                GoodsName: info["商品名称"],
                GoodsImage: info["商品主图"],
                GoodsToken: info["淘口令(30天内有效)"],
                Price: info["商品价格(单位：元)"],
                Discount: Discount,
                DiscountToken: info["优惠券淘口令(30天内有效)"],
                DiscountTime: Math.round(
                  new Date(info["优惠券结束时间"]).getTime() / 1000
                ).toString(),
                DiscountEndTime: Math.round(
                  new Date(info["优惠券开始时间"]).getTime() / 1000
                ).toString(),
                Amount: (
                  parseFloat(info["商品价格(单位：元)"]) - parseFloat(Discount)
                ).toFixed(2), //券后价格，实际购买价格
                Commission: info["佣金"],
                Sales: info["商品月销量"],
                Remark: ""
              });
              id++;
              console.log(JSON.stringify(this.data));
            });
            console.log(JSON.stringify(this.data));
          } else {
            console.warn("表格数据为空！");
          }
          that.outputs = []; // 清空接收数据
          // 编辑数据
          ws.map(i => {
            const sheetData = {
              address: ws[i].addr,
              value: ws[i].value
            };
            that.outputs.push(sheetData);
            return "";
          });
          this.$refs.upload.value = "";
        } catch (e) {
          return false;
        }
      };
      fileReader.readAsBinaryString(files[0]);
    }
  }
};
</script>
